package cn.springcloud.fix.consumer.controller;

import cn.springcloud.fix.common.cache.annotation.RedisCache;
import cn.springcloud.fix.common.cache.entity.CacheScope;
import cn.springcloud.fix.common.core.base.R;
import cn.springcloud.fix.common.log.annotation.AsyncLog;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@Slf4j
@RefreshScope
@RestController
public class ConsumerController {

    @Value("${spring.application.name}")
    private String applicationName;

    @Value("${eureka.client.service-url.defaultZone}")
    private String eurekaServers;

    @Value("${server.port}")
    private String port;

    // @Autowired
    // private UserFeignClient userFeignClient;
    //
    // @Autowired
    // private AdminFeignClient adminFeignClient;

    @Autowired
    private RestTemplate restTemplate;

    private static final String REST_URL_PREFIX = "http://SPRINGCLOUD-PROVIDER";

    @AsyncLog("hello")
    @GetMapping(value = "/test")
    public R<Object> test() {
        return R.SUCCESS(applicationName);
    }

    @RedisCache(pre = "PRE", key = "ttttt", scope = CacheScope.consumer, expire = 7200)
    @GetMapping(value = "/cn/springcloud/fix/consumer/discovery")
    public R<Object> discovery() {
        return R.ERROR();
        // return restTemplate.getForObject(REST_URL_PREFIX + "/discovery", Object.class);
    }

    @GetMapping("/config")
    public String getConfig() {
        String str = "applicationName: " + applicationName + "\t eurekaServers:" + eurekaServers + "\t port: " + port;
        System.out.println("******str: " + str);
        return "applicationName: " + applicationName + "\t eurekaServers:" + eurekaServers + "\t port: " + port;
    }

    @GetMapping("/user/{id}")
    @HystrixCommand(fallbackMethod = "findByIdFallback")
    public Object findById(@PathVariable Long id) {
        return restTemplate.getForObject(REST_URL_PREFIX + "/discovery", Object.class);
    }

    // @GetMapping("/user2/{id}")
    // public Object findById2(@PathVariable Long id) {
    //     return this.userFeignClient.findById(id);
    // }
    //
    // @GetMapping("/admin/{id}")
    // public Object findAdminById(@PathVariable Long id) {
    //     return this.adminFeignClient.findById(id);
    // }

    public Object findByIdFallback(Long id, Throwable throwable) {
        log.error("进入回退方法", throwable);
        return "ok";
    }
}
